package br.com.marcelo.reservasis.client.pagina.reserva;

import br.com.aroeirasoftware.gwtcomponents.client.components.ASApplication;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASButton;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASComboBox;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASForm;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASMessagePanel;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASMessagePanel.ASMessageSeverity;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASOperation;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASPage;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASSearcher;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASTableDetail;
import br.com.aroeirasoftware.gwtcomponents.client.components.ASTogglePanel;
import br.com.aroeirasoftware.gwtcomponents.client.i18n.ASGWTComponentsI18N;
import br.com.marcelo.reservasis.client.i18n.ReservaSISI18N;
import br.com.marcelo.reservasis.client.pagina.hospede.HospedeCriarAlterarPagina;
import br.com.marcelo.reservasis.client.pagina.hospede.HospedePesquisarPagina;
import br.com.marcelo.reservasis.client.services.reservaestadia.ReservaEstadiaUIService;
import br.com.marcelo.reservasis.client.util.ComboBoxUtil;
import br.com.marcelo.reservasis.domain.model.Apartamento;
import br.com.marcelo.reservasis.domain.model.Hospede;
import br.com.marcelo.reservasis.domain.model.ReservaEstadia;
import br.com.marcelo.reservasis.domain.model.TipoApartamento;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Marcelo
 */
public class HospedagemCriarAlterarPagina extends ASPage {

    private ASButton bConfirmar;
    private ASButton bCancelar;
    private ClickHandler clickHandler;
    private ASTogglePanel painelPrincipal;
    private ASForm form;
    private ASOperation operacao;
    private ReservaEstadia reservaEstadia;
    private ASTableDetail tabelaDetalhes;
    private ASSearcher<Hospede> pesquisador;

    public HospedagemCriarAlterarPagina(ASPage paginaAnterior, ASApplication aplicacao, String titulo, String subtitulo) {
        super(paginaAnterior, aplicacao, titulo, subtitulo);
        this.operacao = ASOperation.CRIACAO;
        reservaEstadia = new ReservaEstadia();
    }

    public HospedagemCriarAlterarPagina(ASPage paginaAnterior, ASApplication aplicacao, String titulo, String subtitulo, ReservaEstadia reservaEstadia) {
        super(paginaAnterior, aplicacao, titulo, subtitulo);
        this.operacao = ASOperation.ALTERACAO;
        this.reservaEstadia = reservaEstadia;
    }

    @Override
    public void configurarComponentes() {
        clickHandler = new ClickHandler() {

            public void onClick(ClickEvent event) {
                Object source = event.getSource();

                if (source == bConfirmar) {
                    boolean formulariosValidos = isFormulariosValidos();

                    if (!formulariosValidos) {
                        ASMessagePanel.getInstance().exibirMensagem(
                                ASGWTComponentsI18N.messages.msgProblemasFormulario(),
                                ASMessagePanel.ASMessageSeverity.ERRO,
                                ASMessagePanel.ASMessageOption.OK);
                        return;
                    }
                    preparar();
                    if (operacao == ASOperation.CRIACAO) {
                        salvar(reservaEstadia);
                    } else if (operacao == ASOperation.ALTERACAO) {
                        alterar(reservaEstadia);
                    }
                }

                if (source == bCancelar) {
                    fechar();
                }
            }
        };

        form = new ASForm();
        form.setCaption(ReservaSISI18N.messages.gDadosPrincipais());

        form.addCampoTextoData("dataChegada", ReservaSISI18N.messages.dataChegada(), false);

        pesquisador = new ASSearcher<Hospede>() {

            @Override
            public void pesquisar() {
                new HospedePesquisarPagina(pesquisador).abrir();
            }

            @Override
            protected void renderizar(Hospede arg0) {
                exibirInformacao(arg0.getNome());
            }
        };

        form.addCampoPesquisador("hospede", ReservaSISI18N.messages.hospede(), true, pesquisador);
        form.addCampoOpcoesComboBox("tipoApartamento", ReservaSISI18N.messages.tipoApartamento(), true, true).addChangeHandler(new ChangeHandler() {

            @Override
            public void onChange(ChangeEvent event) {
                ComboBoxUtil.preencherComboBoxApartamento((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento"),
                        (((ASComboBox<TipoApartamento>) form.getComponenteCampo("tipoApartamento")).getValue()));
            }
        });
        form.addCampoOpcoesComboBox("apartamento", ReservaSISI18N.messages.apartamento(), false, true).addChangeHandler(new ChangeHandler() {

            @Override
            public void onChange(ChangeEvent event) {
                if (tabelaDetalhes != null) {
                    tabelaDetalhes.removeFromParent();
                }
                tabelaDetalhes = new ASTableDetail("20%");
                tabelaDetalhes.addLinha(ReservaSISI18N.messages.numeroApartamento(),
                        (((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento")).getValue()) != null
                        ? ((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento")).getValue().getNumApart().toString() : "");
                tabelaDetalhes.addLinha(ReservaSISI18N.messages.numeroQuarto(),
                        (((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento")).getValue()) != null
                        ? ((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento")).getValue().getNumQuartosApart().toString() : "");
                tabelaDetalhes.addLinha(ReservaSISI18N.messages.descricaoApartamento(),
                        (((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento")).getValue()) != null
                        ? ((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento")).getValue().getDescricaoApart() : "");
                if ((((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento")).getValue() != null)) {
                    form.addWidget(tabelaDetalhes);
                }
            }
        });



        form.focalizarPrimeiroCampo();

        painelPrincipal = new ASTogglePanel(ReservaSISI18N.messages.reservaEstadia());
        painelPrincipal.setWidth("100%");

        painelPrincipal.add(form);

        add(painelPrincipal);

        bConfirmar = new ASButton(ASGWTComponentsI18N.messages.btnConfirmar(), clickHandler);
        bConfirmar.addEstiloDefault();
        bCancelar = new ASButton(ASGWTComponentsI18N.messages.btnCancelar(), clickHandler);

        carregarCombo();

        addComando(bConfirmar);
        addComando(bCancelar);
    }

    @Override
    public void configurarDados() {
        if (operacao == ASOperation.ALTERACAO) {
            ReservaEstadiaUIService.Async.getInstance().getPorId(reservaEstadia.getIdreserva(), new AsyncCallback<ReservaEstadia>() {

                public void onFailure(Throwable caught) {
                    ASMessagePanel.getInstance().exibirMensagem("Erro ao recuperar",
                            ASMessageSeverity.ERRO, ASMessagePanel.ASMessageOption.OK);
                }

                public void onSuccess(ReservaEstadia result) {
                    reservaEstadia = result;

                    Map<String, Object> valores = new HashMap<String, Object>();
                    valores.put("dataChegada", reservaEstadia.getDatachegada());
                    valores.put("hospede", reservaEstadia.getHospede() != null ? reservaEstadia.getHospede().getNome() : "");

                    ((ASComboBox<TipoApartamento>) form.getComponenteCampo("tipoApartamento")).setValue(result.getApartamento() != null
                            ? result.getApartamento().getTipoApartamento() : null);

                    ((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento")).setValue(result.getApartamento());

                    form.setValue(valores);
                }
            });
        }
    }

    public void remove(ASForm fom) {
        painelPrincipal.remove(fom);
    }

    public void salvar(final ReservaEstadia reservaEstadia) {
        ReservaEstadiaUIService.Async.getInstance().salvar(reservaEstadia, new AsyncCallback<Integer>() {

            public void onFailure(Throwable caught) {
                ASMessagePanel.getInstance().exibirMensagem(
                        ReservaSISI18N.messages.msgErro(
                        ReservaSISI18N.messages.gCriar(), caught),
                        ASMessageSeverity.ERRO, ASMessagePanel.ASMessageOption.OK);
            }

            public void onSuccess(Integer result) {
                reservaEstadia.setIdreserva(result);


                ASMessagePanel.getInstance().exibirMensagem(
                        ReservaSISI18N.messages.msgSucesso(
                        ReservaSISI18N.messages.reservaEstadia(),
                        "",
                        ReservaSISI18N.messages.gCriado()),
                        ASMessageSeverity.SUCESSO, ASMessagePanel.ASMessageOption.OK, new Command() {

                    public void execute() {
                        fechar();
                    }
                });
            }
        });
    }

    public void alterar(final ReservaEstadia reservaEstadia) {
        ReservaEstadiaUIService.Async.getInstance().atualizar(reservaEstadia, new AsyncCallback<Void>() {

            public void onFailure(Throwable caught) {
                ASMessagePanel.getInstance().exibirMensagem(
                        ReservaSISI18N.messages.msgErro(
                        ReservaSISI18N.messages.gAtualizar(), caught),
                        ASMessageSeverity.ERRO, ASMessagePanel.ASMessageOption.OK);
            }

            public void onSuccess(Void result) {

                ASMessagePanel.getInstance().exibirMensagem(
                        ReservaSISI18N.messages.msgSucesso(
                        ReservaSISI18N.messages.reservaEstadia(),
                        "",
                        ReservaSISI18N.messages.gAtualizado()),
                        ASMessageSeverity.SUCESSO, ASMessagePanel.ASMessageOption.OK, new Command() {

                    public void execute() {
                        fechar();
                    }
                });
            }
        });
    }

    public void preparar() {

        reservaEstadia.setDatachegada((Date) form.getValue().get("dataChegada"));
        reservaEstadia.setHospede(((ASSearcher<Hospede>) form.getComponenteCampo("hospede")).getValue());
        reservaEstadia.setApartamento(((ASComboBox<Apartamento>) form.getComponenteCampo("apartamento")).getValue());
        if (operacao.equals(ASOperation.CRIACAO)) {
            Short hospedagem = new Short("2");
            reservaEstadia.setReserva(hospedagem);
        }
    }

    public void carregarCombo() {
        ComboBoxUtil.preencherComboBoxTipoApartamento((ASComboBox<TipoApartamento>) form.getComponenteCampo("tipoApartamento"));
    }

    public boolean isFormulariosValidos() {
        boolean result = true;
        if (!form.isValido()) {
            result = false;
        }
        return result;
    }
}
